from time import sleep

from playwright.sync_api import Page
from typing import Dict, Any

from service.ResDataService import get_end_data
from tools.Result import success_result, error_result
from tools.HtmlPageService import get_selector_text

# 全局存储响应数据（可根据需求调整）
response_data = {}


def handle_response(response):
    """响应处理器（带数据收集功能）"""
    global response_data
    # 记录所有响应URL

    if "getBidCorpVoByCode" in response.url:
        try:
            response_data =  response.json()
        except:
            # 回退到文本格式
            text = response.text()
            response_data = text


def get_html_detail(page: Page, detail_url: str) -> Dict[str, Any]:
    """获取页面详情并捕获响应数据"""
    global response_data
    # 清空历史数据
    response_data = {}
    # 设置响应监听器
    page.on("response", handle_response)
    try:

        page.goto( detail_url,  wait_until="load",  timeout=15000 )
        # 等待关键元素出现（根据实际页面调整）
        page.wait_for_timeout(800)

        status_name = get_selector_text(page, ".info-box .status")
        status_name="正在进行" if status_name=="限时竞价" else status_name


        # 返回收集到的响应数据
        return success_result("获取成功", get_result(response_data,status_name))

    except Exception as e:
        return error_result(f"页面加载失败: {str(e)}")


def get_result(data,status_name:str):


    return get_end_data(data.get("data",{}).get("startPrice",""), data.get("data",{}).get("currPrice",""), status_name)